package com.aptech.dao;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.aptech.model.UpdateUser;
import com.aptech.model.Userprofile;
import com.aptech.session.GetSessionFactory;
import com.opensymphony.xwork2.ActionContext;

public class UserOperateDao {
	
	
	//添加用户
	public String AddUser(Userprofile user){
		Session session=GetSessionFactory.getInstance().getSessionFactory().openSession();
		try{
		session.save(user);
		session.beginTransaction().commit();
		return "success";
		}catch(Exception e){
			session.beginTransaction().rollback();
			return "error";
		}finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	//删除用户
	public void deleteUser(Userprofile user){
	
	}
	
	//修改用户
	public String updateUser(UpdateUser user,String name){
		Session session=GetSessionFactory.getInstance().getSessionFactory().openSession();
		ActionContext context=ActionContext.getContext();
		
		//先查询用户信息
		Userprofile user1=this.selectUser(name);
		
		//判断用户名是否已被使用
		if(!name.equals(user.getUsername())){
			String sql="select * from Userprofile where username=? and id!=?";
			Query query=session.createSQLQuery(sql);
			query.setParameter(0,user.getUsername());
			query.setParameter(1, user1.getId());
			Object o1=query.uniqueResult();
			if(o1!=null){
				return "nameerror";
			}
		}
		
		
		//将返回的信息写入到新的user对象
		
		user1.setUsername(user.getUsername());
		user1.setAge(user.getAge().toString());
		user1.setAddress(user.getAddress());
		user1.setSex(user.getSex());
		user1.setPhone(user.getPhone());	
		
		
		//执行语句，将对象写入表格
		try{
		session.update(user1);
		session.beginTransaction().commit();
		
		//因为用户存在修改用户名的操作，故在修改成功后，重新将用户名添加到Session中
		context.getSession().put("isLogin",user.getUsername());
		return "success";
		}catch(Exception e){
			session.beginTransaction().rollback();
			return "error";
		}finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	//根据用户名查询用户信息
	public Userprofile selectUser(String name){
		Session session =GetSessionFactory.getInstance().getSessionFactory().openSession();
		try{
		String hql="from Userprofile where username=:deng";
		Query query=session.createQuery(hql);
		query.setParameter("deng",name);
		List l=query.list();
		Userprofile user=(Userprofile)l.get(0);
		return user;
		}finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	//注销用户,将放入在Session中的用户信息移除
	public void logoutUser(){
		ActionContext context=ActionContext.getContext();
		context.getSession().remove("isLogin");
		context.getSession().remove("lv");
	}
}
